﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;
using static System.Diagnostics.Process;

namespace Project_1
{
    /// <summary>
    /// 1.7 线程优先级
    /// </summary>
    public class Unit_1_07
    {
        /*
         * 设置线程的优先级
         * thread.Priority=ThreadPriority.Highest;
         */
        public static void Go()
        {
            WriteLine($"当前线程名：{CurrentThread.Name},线程优先级：{CurrentThread.Priority}");
            WriteLine("在所有可用的内核上运行");
            RunThreads();
            Sleep(TimeSpan.FromSeconds(2));
            WriteLine("在单核上运行");
            GetCurrentProcess().ProcessorAffinity=new IntPtr(1);
            RunThreads();
        }
        static void RunThreads()
        {
            var sample = new ThreadSample();

            var threadOne = new Thread(sample.CountNumbers);
            threadOne.Name = "threadOne";
            var threadTwo = new Thread(sample.CountNumbers);
            threadTwo.Name = "threadTwo";
            threadOne.Priority = ThreadPriority.Highest;
            threadTwo.Priority = ThreadPriority.Lowest;
            threadOne.Start();
            threadTwo.Start();

            Sleep(TimeSpan.FromSeconds(2));
            sample.stop();
        }

        class ThreadSample
        {
            private bool _isStopped = false;

            public void stop()
            {
                _isStopped = true;
            }

            public void CountNumbers()
            {
                long counter = 0;
                while (!_isStopped)
                    counter++;
                WriteLine($"{CurrentThread.Name} with {CurrentThread.Priority,11} has a count= {counter,13:NO}");
            }
        }
    }
}
